﻿<%@ Page Language="c#" Debug="true" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Collections.Specialized" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Globalization" %>
<!-- #Include File="classes/query.aspx -->
<!-- #Include File="classes/command.aspx -->

<script runat="server">
    String errorMsg = null;
    String errorDetail = null;
    NameValueCollection args = null;
    Query query = null;
    ArrayList layerNames = null;
</script>

<%
    try
    {
        InitializeWebTier();
        args = GetRequestParameters();
        query = new Query(args);
        layerNames = query.GetMapLayerNames();
    }
    catch (MgException e)
    {
        errorMsg = e.GetExceptionMessage();
        errorDetail = e.GetDetails();
    }
    //errorMsg.Length 
%>
<html>
<head>
    <title>îçåìì äãåçåú</title>
    <link rel="stylesheet" href="../../../styles/gt.css" type="text/css">

    <script language="javascript" src="../../../viewerfiles/browserdetect.js"></script>

    <script language="javascript" src="../json.js"></script>

    <script language="javascript">

        var READY_STATE_UNINITIALIZED = 0;
        var READY_STATE_LOADING = 1;
        var READY_STATE_LOADED = 2;
        var READY_STATE_INTERACTIVE = 3;
        var READY_STATE_COMPLETE = 4;

        var ICON_EXPAND = "../../../stdicons/nav_band_expand.gif";
        var ICON_HIDE = "../../../stdicons/nav_band_contract.gif";

        var session = '<%= GetParameter(args, "SESSION") %>';
        var mapName = '<%= GetParameter(args, "MAPNAME") %>';

        var strOps = '<%= query.getStrOp() %>'.parseJSON();
        var numOps = '<%= query.getNumOp() %>'.parseJSON();
        var strOpsVal = '<%= query.getStrOpVal() %>'.parseJSON();
        var numOpsVal = '<%= query.getNumOpVal() %>'.parseJSON();
        var queryReqHandler = null;
        var spatialFilterGeomText = null;
        var properties = null;
        var selectionXML = null;
        var results;

        function ShowHiddenArea() {
            if (document.getElementById("spatialFilter").checked) {
                var spatialFilterArea = document.getElementById("expandedAreaSpatialFilter");
                var icon = document.getElementById("spatialFilterAreaExpander");
                if (spatialFilterArea.style.display == "none") {
                    icon.src = ICON_HIDE;
                    spatialFilterArea.style.display = "block";
                }
            }
            ToggleExecuteButton();
        }
        
        function ShowHideArea(icon, id) {
            var node = document.getElementById(id);
            if (node.style.display == "none") {
                icon.src = ICON_HIDE;
                node.style.display = "block";
            }
            else {
                icon.src = ICON_EXPAND;
                node.style.display = "none";
            }
            ToggleExecuteButton();
        }

        function ShowLoading() {
            divLoading.style.opacity = 0.7;
            divLoading.style.filter = "alpha(Opacity=70)";
            divLoading.style.display = "block";
            divLoading.style.cursor = "wait";
        }

        function HideLoading() {
            divLoading.style.display = "none";
            divLoading.style.cursor = "";
        }

        function OnLayerChange() {
            ShowLoading();
            var layerSelect = document.getElementById("layerSelect");
            var propertySelect = document.getElementById("propertySelect");
            var outputSelect = document.getElementById("outputSelect");

            reqParams = "COMMAND=<%=Command.GETLAYERPROPERTIES%>";
            reqParams += "&SESSION=" + encodeURIComponent(session);
            reqParams += "&MAPNAME=" + encodeURIComponent(mapName);
            reqParams += "&LAYERNAME=" + encodeURIComponent(layerSelect.value);

            if (msie)
                reqHandler = new ActiveXObject("Microsoft.XMLHTTP");
            else
                reqHandler = new XMLHttpRequest();

            reqHandler.open("POST", "querycontroller.aspx", false);
            reqHandler.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            reqHandler.send(reqParams);
            properties = reqHandler.responseText.parseJSON();

            propertySelect.options.length = 0;
            outputSelect.options.length = 0;
            for (var i = 0; i < properties.length; i++) {
                propertySelect.options[i] = new Option(properties[i].aliasname, i, false, false);
                outputSelect.options[i] = new Option(properties[i].aliasname, i, false, false);
            }
            OnPropertyChange();
        }

        function OnPropertyChange() {
            var propertySelect = document.getElementById("propertySelect");
            var operatorSelect = document.getElementById("operatorSelect");

            operatorSelect.options.length = 0;
            if (propertySelect.selectedIndex >= 0) {
                var ops = null;
                if (properties[propertySelect.value].isString)
                    ops = strOps;
                else
                    ops = numOps;

                for (var i = 0; i < ops.length; i++) {
                    operatorSelect.options[i] = new Option(ops[i], i, false, false);
                }
            }
            HideLoading();
        }

        function OnToggleSpatialFilter() {
            if (spatialFilterGeomText != null) {
                ToggleSpatialFilter(document.getElementById("spatialFilter").checked);
            }
            ToggleExecuteButton();
        }

        function OnDigitizeRectangle() {
            parent.parent.mapFrame.DigitizeRectangle(OnRectangleDigitized);
        }

        function OnRectangleDigitized(rectangle) {
            var geomText = "5,"
            + rectangle.Point1.X + "," + rectangle.Point1.Y + ","
            + rectangle.Point2.X + "," + rectangle.Point1.Y + ","
            + rectangle.Point2.X + "," + rectangle.Point2.Y + ","
            + rectangle.Point1.X + "," + rectangle.Point2.Y + ","
            + rectangle.Point1.X + "," + rectangle.Point1.Y;

            ShowSpatialFilter(geomText);
        }

        function OnDigitizePolygon() {
            parent.parent.mapFrame.DigitizePolygon(OnPolyonDigitized);
        }

        function OnPolyonDigitized(polygon) {
            var geomText = polygon.Count;
            for (var i = 0; i < polygon.Count; i++) {
                geomText += "," + polygon.Point(i).X + "," + polygon.Point(i).Y;
            }

            ShowSpatialFilter(geomText);
        }

        function OnClearSpatialFilter() {
            document.getElementById("spatialFilter").checked = false;
            OnToggleSpatialFilter();

            spatialFilterGeomText = null;
            ToggleExecuteButton();
        }

        function ShowSpatialFilter(geomText) {
            reqParams = "COMMAND=<%=Command.SHOWSPATIALFILTER%>";
            reqParams += "&SESSION=" + encodeURIComponent(session);
            reqParams += "&MAPNAME=" + encodeURIComponent(mapName);
            reqParams += "&GEOMTEXT=" + encodeURIComponent(geomText);

            if (msie)
                reqHandler = new ActiveXObject("Microsoft.XMLHTTP");
            else
                reqHandler = new XMLHttpRequest();

            reqHandler.open("POST", "querycontroller.aspx", false);
            reqHandler.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            reqHandler.send(reqParams);

            spatialFilterGeomText = geomText;
            document.getElementById("spatialFilter").checked = true;
            parent.parent.Refresh();
            ToggleExecuteButton();
        }

        function ToggleSpatialFilter(visible) {
            reqParams = "COMMAND=<%=Command.TOGGLESPATIALFILTER%>";
            reqParams += "&SESSION=" + encodeURIComponent(session);
            reqParams += "&MAPNAME=" + encodeURIComponent(mapName);
            reqParams += "&VISIBLE=" + encodeURIComponent(visible);

            if (msie)
                reqHandler = new ActiveXObject("Microsoft.XMLHTTP");
            else
                reqHandler = new XMLHttpRequest();

            reqHandler.open("POST", "querycontroller.aspx", false);
            reqHandler.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            reqHandler.send(reqParams);

            parent.parent.Refresh();
        }

        function ExecuteQuery() {
            ShowLoading();
            reqParams = "COMMAND=<%=Command.EXECUTEQUERY%>";
            reqParams += "&SESSION=" + encodeURIComponent(session);
            reqParams += "&MAPNAME=" + encodeURIComponent(mapName);
            reqParams += "&LAYERNAME=" + encodeURIComponent(layerSelect.value);

            if (document.getElementById("propertyFilter").checked) {
                reqParams += "&USEPROPERTYFILTER=true";
                reqParams += "&FILTERSTRING=" + encodeURIComponent(buildFilter());
            }
            else {
                reqParams += "&USEPROPERTYFILTER=false";
            }

            if (document.getElementById("spatialFilter").checked && spatialFilterGeomText != null) {
                reqParams += "&USESPATIALFILTER=true";
                reqParams += "&GEOMTEXT=" + encodeURIComponent(spatialFilterGeomText);
            }
            else {
                reqParams += "&USESPATIALFILTER=false";
            }
            reqParams += "&OUTPUTPROPERTY=" + encodeURIComponent(properties[document.getElementById("outputSelect").value].name);
            reqParams += "&QUERYMAX=" + encodeURIComponent(document.getElementById("queryMax").value);

            if (msie)
                queryReqHandler = new ActiveXObject("Microsoft.XMLHTTP");
            else
                queryReqHandler = new XMLHttpRequest();

            queryReqHandler.onreadystatechange = OnReadyStateChange;
            queryReqHandler.open("POST", "querycontroller.aspx", true);
            queryReqHandler.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            document.getElementById("executeBtn").disabled = true;

            queryReqHandler.send(reqParams);
        }

        function SelectFeature() {
            ShowLoading();
            var arSelected = new Array();
            var resultSelect = document.getElementById("resultSelect");
            while (resultSelect.selectedIndex != -1) {
                arSelected.push(results[resultSelect.selectedIndex].idList);
                resultSelect.options[resultSelect.selectedIndex].selected = false;
            }
            if (arSelected.length <= 0) {
                for (var i = 0; i < resultSelect.options.length; i++) {
                    arSelected.push(results[i].idList);
                }
            }

            reqParams = "COMMAND=<%=Command.GETSELECTIONXML%>";
            reqParams += "&SESSION=" + encodeURIComponent(session);
            reqParams += "&MAPNAME=" + encodeURIComponent(mapName);
            reqParams += "&LAYERNAME=" + encodeURIComponent(layerSelect.value);
            reqParams += "&IDLIST=" + arSelected.toJSONString(); //results[resultSelect.value].idList.toJSONString();

            if (msie)
                reqHandler = new ActiveXObject("Microsoft.XMLHTTP");
            else
                reqHandler = new XMLHttpRequest();

            reqHandler.open("POST", "querycontroller.aspx", false);
            reqHandler.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            reqHandler.send(reqParams);
            selectionXml = reqHandler.responseText;
            selectionXML = selectionXml;
            parent.parent.mapFrame.SetSelectionXML(selectionXml);
            HideLoading();
        }

        function ZoomToFeature() {
            var resultSelect = document.getElementById("resultSelect");
            var scaleInput = document.getElementById("scaleInput");
            scale = scaleInput.value;
            scale = ((scale == 0) ? 10000 : scale);
            scale = parseFloat(scale + String(".0"));

            feature = results[resultSelect.value];
            if (feature.centerX == null) {
                SelectFeature();
                parent.parent.mapFrame.ZoomToSelection();
            }
            else
                parent.parent.mapFrame.ZoomToView(feature.centerX, feature.centerY, scale, true);
        }

        function OnReadyStateChange() {
            var ready = queryReqHandler.readyState;

            if (ready == READY_STATE_COMPLETE) {
                results = queryReqHandler.responseText.parseJSON();
                var resultSelect = document.getElementById("resultSelect");
                resultSelect.options.length = 0;
                for (var i = 0; i < results.length; i++) {
                    resultSelect.options[i] = new Option(results[i].displayValue, i, false, false);
                }
                OnResultChange();

                document.getElementById("executeBtn").disabled = false;
                queryReqHandler = null;
                HideLoading();
            }
        }

        function OnResultChange() {
            var resultSelect = document.getElementById("resultSelect");
            var scaleInput = document.getElementById("scaleInput");
            var zoomBtn = document.getElementById("zoomBtn");
            var selectBtn = document.getElementById("selectBtn");
            var showreportBtn = document.getElementById("showreportBtn");

            // Featur Button
            if (resultSelect.selectedIndex >= 0) {
                scaleInput.disabled = false;
                zoomBtn.disabled = false;
                selectBtn.disabled = false;
            }
            else {
                scaleInput.disabled = true;
                zoomBtn.disabled = true;
                selectBtn.disabled = true;
            }

            // Report Button
            if (resultSelect.length > 0)
                showreportBtn.disabled = false;
            else
                showreportBtn.disabled = true;
        }

        function OnLoad() {
            OnLayerChange();
            OnResultChange();
            HideLoading();
        }

        function OnUnload() {
            ToggleSpatialFilter(false);
        }
        function ShowReport() {
            if (selectionXML == null) SelectFeature();
            try {
                var keys = new Array();
                var values = new Array();
                keys[0] = "SESSION"; values[0] = session;
                keys[1] = "MAPNAME"; values[1] = mapName;
                keys[2] = "MAPDEFINITION"; values[2] = "";
                keys[3] = "mgkey"; values[3] = selectionXML; //parent.parent.mapFrame.GetSelectionXML(); 
                keys[4] = "SHOWNAMEHEADER"; values[4] = "false";
                keys[5] = "ResourceId"; values[5] = "";
                keys[6] = "LAYER"; values[6] = document.all("layerSelect").value;
                openWindowWithPost("../Report/viewreportlayout.aspx", "Report", keys, values);
            } catch (e) {
                alert('òìéê ìáçåø ñåâ ãåç îøùéîä');
            }
        }
        function openWindowWithPost(url, name, keys, values) {
            var newWindow = window.open(url, name);
            if (!newWindow) return false;
            var html = "";
            html += "<html><head></head><body>\n<form id='formid' method='post' action='" + url + "'>\n";
            if (keys && values && (keys.length == values.length))
                for (var i = 0; i < keys.length; i++) {
                html += "<input type='hidden' name='" + keys[i] + "' value='" + values[i] + "'/>\n";
            }
            html += "</form><script type='text/javascript'>document.getElementById('formid').submit()</";
            html += "script></body></html>";
            newWindow.document.write(html);
            return newWindow;
        }

        //Filter builder
        function AddToFilter() {
            var value = null;
            var property = properties[document.getElementById("propertySelect").value];
            var fValue = null;
            var fText = null;
            fText = property.aliasname + " ";

            fValue = property.name;
            if (!property.isString) {
                fText += "<b>" + numOps[document.getElementById("operatorSelect").value] + "</b> ";
                fValue += "|" + numOpsVal[document.getElementById("operatorSelect").value] + "|";
            }
            else {
                fText += "<b>" + strOps[document.getElementById("operatorSelect").value] + "</b> ";
                fValue += strOpsVal[document.getElementById("operatorSelect").value];
            }
            fText += document.getElementById("valueInput").value;
            fValue += document.getElementById("valueInput").value;
            if (document.getElementById("valueInput").value.length == 0) return;
            document.getElementById("valueInput").value = "";
            insertToFilter(fText, fValue);
        }

        var alternate = false;
        var idx = 0;

        function insertToFilter(text, value) {
            var tbl = document.getElementById("tableFilter");

            var color = alternate ? "White" : "Silver";
            alternate = !alternate;
            var newRow = tbl.insertRow(idx);
            newRow.style.backgroundColor = color;
            var linkCell = newRow.insertCell(0);
            linkCell.className = "RegText";
            linkCell.innerHTML = "<a href='#' onclick='removeFromFilter(this)'><img src='../../../stdicons/filter (delete).png' width='16' height='16' title='îç÷'  style='border:none'/></a>";
            linkCell.width = 16;

            var newCell = newRow.insertCell(1);
            newCell.className = "RegText";
            newCell.innerHTML = text;
            newCell.className = "RegText";
            newCell.innerHTML = text;

            var hidden = document.createElement("input");
            hidden.type = "hidden";
            hidden.value = value;
            newCell.appendChild(hidden);

            document.getElementById("executeBtn").disabled = "";
            document.getElementById("layerSelect").disabled = "disabled";

            idx++;
            if (idx > 0) document.getElementById("panelLogic").style.display = "";
            ToggleExecuteButton();
        }

        function removeFromFilter(obj) {
            var tbl = document.getElementById("tableFilter");

            var num_tr = obj.parentNode.parentNode.sectionRowIndex;
            tbl.deleteRow(num_tr)

            idx--;
            if (idx <= 1) {
                document.getElementById("panelLogic").style.display = "none";
            }
            if (idx == 0) {
                document.getElementById("layerSelect").disabled = "";
            }
            ToggleExecuteButton();
        }

        function buildFilter() {
            var tbl = document.getElementById("tableFilter");
            var hiddens = tbl.getElementsByTagName("input");
            var radios = document.getElementById("panelLogic").getElementsByTagName("input");

            var logic;

            for (var ix = 0; ix < radios.length; ix++) {
                if (radios[ix].checked === true) logic = radios[ix].value;
            }
            var filter = '';
            for (var i = 0; i < hiddens.length; i++) {
                if (i > 0)
                    filter += logic;
                filter += hiddens[i].value;
            }
            return filter;
        }

        function ToggleExecuteButton() {
            var executeButton = document.getElementById("executeBtn");
            
            var chbExprFilter = document.getElementById("propertyFilter");
            var chbSpatialFilter = document.getElementById("spatialFilter");

            if ((chbExprFilter.checked && idx > 0) || (chbSpatialFilter.checked && spatialFilterGeomText != null)) {
                executeButton.disabled = false;
            }
            else executeButton.disabled = true;
        }
    </script>

</head>
<body onload="OnLoad()" onunload="OnUnload()" style="margin: 5px">
    <div id="divLoading" style="background: #C8C8C8 url('..\..\stdicons\ajax-loader.gif') no-repeat center center;
        position: absolute; width: 100%; height: 100%; display: none;">
    </div>
    <% if (errorMsg == null)
       {%>
    <table dir="rtl" class="RegText" border="0" cellspacing="0" width="100%">
        <tr>
            <td class="Title">
                îçåìì ùàéìúåú<hr>
            </td>
        </tr>
        <!-- Filter Part -->
        <tr>
            <td class="SubTitle">
                áçø ùëáä îøùéîä
            </td>
        </tr>
        <tr>
            <td>
                ùëáä:
            </td>
        </tr>
        <tr>
            <td class="RegText">
                <select size="1" class="Ctrl" id="layerSelect" onchange="OnLayerChange()" style="width: 100%">
                    <%
                        String selected = "selected";
                        String optvl = "";
                        String opttx = "";
                        foreach (String layerName in layerNames)
                        {
                            optvl = layerName.Substring(layerName.IndexOf("%") + 1, layerName.Length - layerName.IndexOf("%") - 1);
                            opttx = layerName.Substring(0, layerName.IndexOf("%"));
                    %>
                    <option value="<%=optvl%>" <%=selected %>>
                        <%=opttx %></option>
                    <%
                        selected = "";
                        }
                    %>
                </select>
            </td>
        </tr>
        <tr>
            <td class="Spacer">
            </td>
        </tr>
        <tr>
            <td class="SubTitle">
                <input class="Ctrl" type="checkbox" id="propertyFilter" onclick="ToggleExecuteButton()" checked="checked" />&nbsp;ñéðåï îéìåìé
            </td>
        </tr>
        <tr>
            <td>
                îàôééï:
            </td>
        </tr>
        <tr>
            <td class="RegText">
                <select size="1" class="Ctrl" id="propertySelect" onchange="OnPropertyChange()" style="width: 100%">
                </select>
            </td>
        </tr>
        <tr>
            <td>
                îàôééï ñéðåï:
            </td>
        </tr>
        <tr>
            <td class="RegText">
                <select size="1" class="Ctrl" id="operatorSelect" style="width: 100%">
                </select>
            </td>
        </tr>
        <tr>
            <td>
                äòøê:
            </td>
        </tr>
        <tr>
            <td class="RegText">
                <input maxlength="100" class="Ctrl" id="valueInput" style="width: 100%">
            </td>
        </tr>
        <tr>
            <td class="Spacer">
            </td>
        </tr>
        <tr>
            <td class="SubTitle">
                äåñó ñéðåï: <a href='#' onclick='AddToFilter()'>
                    <img src='../../../stdicons/filter (add).png' width='16' height='16' title='îç÷' style='border: none'
                        alt='' /></a> <span id="panelLogic" style="display: none;"><b>åâí</b><input type='radio'
                            name='radioLogic' value='[&amp;]' checked="checked" />
                            <b>àå</b><input type='radio' name='radioLogic' value='[|]' />
                        </span>
            </td>
        </tr>
        <tr>
            <td class="RegText" style="text-align: center">
                <table id="tableFilter" style="border: solid 1px black; width: 90%;">
                </table>
            </td>
        </tr>
        <!-- End Filter Part -->
        <!-- Spatial Filter Part -->
        <tr>
            <td class="Spacer">
            </td>
        </tr>
        <tr>
            <td class="SubTitle">
                <input class="Ctrl" type="checkbox" onclick="ShowHiddenArea()" onchange="OnToggleSpatialFilter()" id="spatialFilter">&nbsp;ñéðåï
                âéàåâøôé áîôä
                <div style="position: absolute; left: 5px;">
                    <img id="spatialFilterAreaExpander" src="../../../stdicons/nav_band_expand.gif" alt="" name="imgExpander" onclick="ShowHideArea(this, 'expandedAreaSpatialFilter')" />
                </div>
            </td>
        </tr>
        <tr id="expandedAreaSpatialFilter" style="display: none">
            <td align="center">
                <input type="button" name="" value="øéáåò" class="Ctrl" id="rectButton" onclick="OnDigitizeRectangle()"
                    style="width: 30%">
                <input type="button" name="" value="îöåìò" class="Ctrl" id="polyButtton" onclick="OnDigitizePolygon()"
                    style="width: 30%">
                <input type="button" name="" value="ð÷ä" class="Ctrl" id="clearButton" onclick="OnClearSpatialFilter()"
                    style="width: 30%">
            </td>
        </tr>
        <!-- End Spatial Filter Part -->
        <!-- Result Part -->
        <tr>
            <td class="Spacer">
                <hr />
            </td>
        </tr>
        <tr>
            <td class="SubTitle">
                úåöàä
            </td>
        </tr>
        <tr>
            <td>
                îàôééï äúåöàä:
            </td>
        </tr>
        <tr>
            <td class="RegText">
                <select size="1" class="Ctrl" id="outputSelect" style="width: 100%">
                </select>
            </td>
        </tr>
        <tr>
            <td class="Spacer">
            </td>
        </tr>
        <tr>
            <td>
                <hr>
            </td>
        </tr>
        <tr>
            <td>
                <input id="executeBtn" class="Ctrl" name="" type="button" onclick="ExecuteQuery()"
                    disabled="disabled" value="áöò" style="width: 60px">
                &nbsp;&nbsp;î÷ñéîåí úåöàåú:&nbsp;
                <input name="" id="queryMax" class="Ctrl" type="text" value="100" size="5">
            </td>
        </tr>
        <tr>
            <td class="Spacer">
            </td>
        </tr>
        <tr>
            <td class="SubTitle">
                úåöàåú
            </td>
        </tr>
        <tr>
            <td>
                <select class="Ctrl" id="resultSelect" multiple="multiple" size="8" onchange="OnResultChange()"
                    style="width: 100%">
                </select>
            </td>
        </tr>
        <tr>
            <td>
                ÷ð"î:&nbsp;<input class="Ctrl" id="scaleInput" type="text" size="4" value="10000">
                <input class="Ctrl" id="zoomBtn" type="button" onclick="ZoomToFeature()" value="äúî÷ã"
                    style="width: 40px">
                <input class="Ctrl" id="selectBtn" type="button" onclick="SelectFeature()" value="áçø"
                    style="width: 40px">
                <input class="Ctrl" id="showreportBtn" type="button" onclick="ShowReport()" value="äöâ ãåç"
                    style="width: 50px">
            </td>
        </tr>
        <!-- End Result Part -->
    </table>
    <% }
       else
       { %>
    <table class="RegText" border="0" cellspacing="0" width="100%%">
        <tr>
            <td class="Title">
                ùâéàä<hr>
            </td>
        </tr>
        <tr>
            <td>
                <%=errorMsg%>
            </td>
        </tr>
        <tr>
            <td>
                <%=errorDetail%>
            </td>
        </tr>
    </table>
    <% } %>
</body>
</html>
